package icu.d4peng.cloud.common.log.generator.spanid;

import com.alibaba.ttl.TransmittableThreadLocal;
import icu.d4peng.cloud.common.log.context.LogContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author d4peng
 * @version 1.0.0
 * @date 2021-12-27 14:02
 * @description DefaultSpanIdGenerator:默认spanId生成器
 */
public class DefaultSpanIdGenerator extends SpanIdGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSpanIdGenerator.class);

    /**
     * 用于存储当前span的下标
     */
    private static final TransmittableThreadLocal<Integer> spanIndex = new TransmittableThreadLocal<>();
    /**
     * 当前Span的下标
     */
    private static final String INITIAL_VALUE = "0";

    @Override
    public String getSpanId() {
        return currentSpanIdTL.get();
    }

    @Override
    public void setSpanId(String spanId) {
        if (StringUtils.isEmpty(spanId)) {
            spanId = INITIAL_VALUE;
        }
        currentSpanIdTL.set(spanId);
        spanIndex.set(Integer.valueOf(INITIAL_VALUE));
    }

    @Override
    public void remove() {
        currentSpanIdTL.remove();
    }

    @Override
    public String generateNextSpanId() {
        synchronized (LogContext.getTraceId()) {
            String currentSpanId = LogContext.getSpanId();
            spanIndex.set(spanIndex.get() + 1);
            String nextSpanId = String.format("%s.%s", currentSpanId, spanIndex.get());
            LOGGER.info("next span id is:{}", nextSpanId);
            return nextSpanId;
        }
    }
}
